<template>
	<div>
		<!-- 添加规格按钮 -->
		<el-form-item>
			<el-button type="primary" @click="addSpecification">添加规格</el-button>
		</el-form-item>

		<!-- 动态规格表单 -->
		<el-form-item v-for="(item, index) in specArray" :key="index">
			<div>
				规格名称：
				<el-input v-model="item.name" placeholder="请输入" style="width: 100px;" />
				<el-button type="danger" @click="removeSpecification(index)">删除规格</el-button>
			</div>
			<el-button type="primary" @click="addSpecList(index)">添加属性</el-button>
			<div v-for="(spec, i) in item.specList" :key="i">
				属性名称：
				<el-input v-model="spec.name" placeholder="请输入" style="width: 100px;" />
				<el-button type="danger" @click="removeSpecList(index, i)">删除属性</el-button>
			</div>
		</el-form-item>

		<!-- 规格列表 -->
		<el-form-item label="规格列表">
			<el-table :data="specifications" border style="width: 100%">
				<el-table-column v-for="(item, index) in specArray" :key="index" :label="item.name" width="180" align="center">
					<template #default="{ row }">
						<el-input v-model="row[item.name]" readonly />
					</template>
				</el-table-column>

				<el-table-column prop="originalPrice" label="商品原价" align="center">
					<template #default="{ row }">
						<el-input v-model="row.originalPrice" placeholder="请输入商品原价" />
					</template>
				</el-table-column>

				<el-table-column prop="price" label="商品售价" align="center">
					<template #default="{ row }">
						<el-input v-model="row.price" placeholder="请输入商品售价" />
					</template>
				</el-table-column>

				<el-table-column prop="sales" label="商品销量" align="center">
					<template #default="{ row }">
						<el-input v-model="row.sales" placeholder="请输入默认商品销量" />
					</template>
				</el-table-column>

				<el-table-column prop="stock" label="商品库存" align="center">
					<template #default="{ row }">
						<el-input v-model="row.stock" placeholder="请输入商品库存" />
					</template>
				</el-table-column>
			</el-table>
		</el-form-item>
	</div>
</template>

<script setup lang="ts">
	import { ref, watch } from 'vue'
	import { convertToGoodsSpecifications , zhuanhuan } from '../goods';
	const props = defineProps({
		data: {
			default: () => ({}),
			type: Object
		}
	})
	// 规格数组
	const specArray = ref<any[]>([])
	// 规格组合数据
	const specifications = ref<any[]>([])
	// 添加新规格
	const addSpecification = () => {
		specArray.value.push({
			name: '',
			specList: []
		})
	}
	// 添加规格属性
	const addSpecList = (index : number) => {
		specArray.value[index].specList.push({
			name: ''
		})
		updateSpecifications()
	}
	// 删除规格属性
	const removeSpecList = (specIndex : number, attrIndex : number) => {
		specArray.value[specIndex].specList.splice(attrIndex, 1)
		updateSpecifications()
	}
	// 删除规格
	const removeSpecification = (index : number) => {
		specArray.value.splice(index, 1)
		updateSpecifications()
	}

	// 更新规格组合数据
	const updateSpecifications = () => {
		const specs = [];
		const attributesList = specArray.value.reduce((result, spec) => {
			const attributeValues = spec.specList.map((attr : { name : any; }) => attr.name).filter((name : any) => name);
			return attributeValues.length ? [...result, attributeValues] : result;
		}, []);

		// 组合所有属性
		const combineAttributes = (arr : any[]) => {
			if (arr.length === 0) return [];
			if (arr.length === 1) return arr[0].map((item : any) => [item]);
			const result = [];
			const restCombination = combineAttributes(arr.slice(1));
			for (const item of arr[0]) {
				for (const combination of restCombination) {
					result.push([item, ...combination]);
				}
			}
			return result;
		};

		const combinations = combineAttributes(attributesList);

		// 使用映射保持原有规格数据
		const existingSpecsMap = new Map<string, any>(
			specifications.value.map(spec => {
				// 仅包含当前specArray的规格属性用于匹配
				const relevantSpec = specArray.value.reduce((acc, specItem) => {
					if (specItem.name in spec) {
						acc[specItem.name] = spec[specItem.name];
					}
					return acc;
				}, {});
				const key = JSON.stringify(relevantSpec);
				return [key, spec];
			})
		);

		combinations.forEach((combination : any[]) => {
			const spec = {};
			specArray.value.forEach((specItem, index) => {
				spec[specItem.name] = combination[index];
			});

			const specKey = JSON.stringify(spec);
			const existingSpec = existingSpecsMap.get(specKey);

			specs.push({
				...spec,
				originalPrice: existingSpec?.originalPrice ?? 0,
				price: existingSpec?.price ?? 0,
				sales: existingSpec?.sales ?? 0,
				stock: existingSpec?.stock ?? 0
			});
		});
		specifications.value = specs;
	};

	const submitForm = () => {
		console.log(specifications.value);
		console.log(JSON.stringify(specifications.value));
		console.log(convertToGoodsSpecifications(specifications.value));
		console.log(zhuanhuan(specifications.value))
		console.log(JSON.stringify(zhuanhuan(specifications.value)))
		return {
			item: zhuanhuan(specifications.value),
			specifications: specifications.value,
			specArray: specArray.value
		}
	}
	if (props.data) {
		specArray.value = JSON.parse(props.data.specArray)
		specifications.value = JSON.parse(props.data.specifications)
	}
	
	
	// 监听规格数组的变化，自动更新规格组合数据
	watch(specArray, updateSpecifications, { deep: true })
	defineExpose({
		submitForm
	})
</script>

<style scoped>
</style>